
#import "XCommon.h"

#import <CommonCrypto/CommonDigest.h>

@implementation XCommon
/**
 @method 获取指定宽度情况ixa，字符串value的高度
 @param value 待计算的字符串
 @param fontSize 字体的大小
 @param andWidth 限制字符串显示区域的宽度
 @result float 返回的高度
 */
+ (float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
    //    CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];//此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
    CGSize sizeToFit = [value boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil].size;
    return sizeToFit.height;
}

+ (float) widthForString:(NSString *)value fontSize:(float)fontSize
{
    //    CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];//此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
    CGSize sizeToFit = [value boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil].size;
    return sizeToFit.width;
}

//判断字符串是否为空
+ (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}


//MD5加密
+ (NSString *)stringByMDFive:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
//URLEncode编码
+ (NSString *)URLEncodedString:(NSString *)sourceString
{
    NSData * UTF8Data = [sourceString dataUsingEncoding:NSUTF8StringEncoding];

    NSString *encodedString = [self urlEncodedString:UTF8Data];
    return encodedString;
}


//+ (NSString *)urlEncodedString:(NSData *)src
//{
//	char *hex = "0123456789ABCDEF";
//	unsigned char * data = (unsigned char*)[src bytes];
//	int len = [src length];
//	NSMutableString* s = [NSMutableString string];
//	for(int i = 0;i<len;i++){
//		unsigned char c = data[i];
//		if( ('a' <= c && c <= 'z')
//		   || ('A' <= c && c <= 'Z')
//		   || ('0' <= c && c <= '9') ){
//			NSString* ts = [[NSString alloc] initWithCString:(char *)&c length:1];
//			
//			[s appendString:ts];
//			[ts release];
//		} else {
//			[s appendString:@"%"];
//			char ts1 = hex[c >> 4];
//			NSString* ts = [[NSString alloc] initWithCString:&ts1 length:1];
//			[s appendString:ts];
//			[ts release];
//			char ts2 = hex[c & 15];
//			ts = [[NSString alloc] initWithCString:&ts2 length:1];
//			[s appendString:ts];
//			[ts release];
//			
//		}
//	}
//	return s;
//}


//判断一个字符串是否为空
+ (BOOL)isNullString:(NSString *)string
{
    if (string == nil || string == NULL) {
        return YES;
    }
    else if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    else if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    
    return NO;
}

//16进制颜色(html颜色值)字符串转为UIColor
+(UIColor *) hexStringToColor: (NSString *) stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    
    if ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

+ (NSString *)dateWithDateline:(NSString *)dateline
{
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:[dateline floatValue]];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
//    //格林威治时间和北京时间差 8 个小时
//    NSString * str2 = [NSString stringWithFormat:@"%@ 08:00:00",str];
//    NSDate * date = [formatter1 dateFromString:str2];
    NSString * dateStr = [formatter stringFromDate:date];
    return dateStr;
}

+ (NSString *)timeWithDateline:(NSString *)dateline
{
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:[dateline floatValue]];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    //    //格林威治时间和北京时间差 8 个小时
    //    NSString * str2 = [NSString stringWithFormat:@"%@ 08:00:00",str];
    //    NSDate * date = [formatter1 dateFromString:str2];
    NSString * dateStr = [formatter stringFromDate:date];
    return dateStr;
}

+ (NSString *)timeFromNowSinceDateline:(NSString *)dateline
{
    NSDate * dt = [NSDate dateWithTimeIntervalSince1970:[dateline floatValue]];
    NSDateFormatter * formatter1 = [[NSDateFormatter alloc] init];
    formatter1.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDateFormatter * formatter2 = [[NSDateFormatter alloc] init];
    formatter2.dateFormat = @"yyyy-MM-dd";
    NSString * str = [formatter2 stringFromDate:[NSDate date]];
    //格林威治时间和北京时间差 8 个小时
    NSString * str2 = [NSString stringWithFormat:@"%@ 08:00:00",str];
    NSDate * date = [formatter1 dateFromString:str2];
    NSTimeInterval aTimer = [date timeIntervalSinceDate:dt];//aTimer 是 dateline 距离现在的时间差
    float days = (float)(aTimer/3600/24);
    NSString * timeStr = @"";
    if (days <= 0) {
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"HH:mm";
        NSString * dataStr = [formatter stringFromDate:dt];
        //        if (dateline.integerValue - 43200 >= 0) {
        //            timeStr = [NSString stringWithFormat:@"下午%@",dataStr];
        //        }else
        //        {
        timeStr = [NSString stringWithFormat:@"今天%@",dataStr];
        //        }
        
    }else if (days>0 && days<=1) {
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"HH:mm";
        NSString * dataStr = [formatter stringFromDate:dt];
//        if (dateline.integerValue - 43200 >= 0) {
//            timeStr = [NSString stringWithFormat:@"下午%@",dataStr];
//        }else
//        {
            timeStr = [NSString stringWithFormat:@"今天%@",dataStr];
//        }
        
    } else if (days>1 && days<=2) {
        
        timeStr = @"昨天";
    }else if (days>2 && days<=3){
        timeStr = @"前天";
        
    }else if (days>3 && days<=4){
        
        timeStr = [self weekDayStr:dt];
        
    }else if (days>4 && days<=5){
        
        timeStr = [self weekDayStr:dt];
        
    }else if (days>5 && days<=6){
        
        timeStr = [self weekDayStr:dt];
    }else if (days>6 && days<=7){
        timeStr = [self weekDayStr:dt];
    }
    else {
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"MM/dd";
        timeStr = [formatter stringFromDate:dt];
    }
    return timeStr;
}

+ (NSString*)weekDayStr:(NSDate *)format
{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps;
    comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:format];
    int nowYear = [comps year];
    int nowMonth = [comps month];
    int nowDay = [comps day];
    int nowWeek = [comps weekday];
    NSString *weekStr = [[NSString alloc] init];
    switch (nowWeek) {
        case 1:
            weekStr = @"星期天";
            break;
        case 2:
            weekStr = @"星期一";
            break;
        case 3:
            weekStr = @"星期二";
            break;
        case 4:
            weekStr = @"星期三";
            break;
        case 5:
            weekStr = @"星期四";
            break;
        case 6:
            weekStr = @"星期五";
            break;
        case 7:
            weekStr = @"星期六";
            break;
            
        default:
            break;
    }
    return weekStr;
}

+(CGFloat)scaleFromWidthOrHeight:(CGFloat)length
{
    return 720.0f/length;
}





@end
